CSS - Grid: cells, areas, and nesting grid


Posted by urlun0404 on 2022-04-18

複習並整理一下前一篇元素定位 ,基本上Grid的元素定位方式可以分為三種,

  1. placed using line numbers
  2. placed using line name
  3. placed by targeting an area of grid

Grid cells and Grid areas

Grid cell 是 Grid 系統中最小的單位;多個相鄰 Grid cells 形成的矩形即 Grid area。例如下圖左將一個容器內部分出 9 個 Grid Cells,而右邊就是將容器內左上4個cells擴展成一個 Grid Area。

Grid Area
在Grid裡面劃分出空間就會產生Cells,所以這裡想要釐清的是如何創造Grid area?(這個大概也是Grid的排版精華了)

MDN 有提到 Grid area 可以在以下時機創造出來:

  1. 元素根據Grid Lines定位
  2. 或者定義 grid-area

grid-area
grid-area 屬性值可以有兩種寫法:

  1. 群組化某個空間的 line numbers
  2. 命名某個空間

下面這是用 grid-area 群組化某個空間的 line numbers的方式,即依序給定 grid-row-startgrid-column-startgrid-row-endgrid-column-end 數值,有點像是綜合 grid-rowgrid-column 的 shorthand 寫法。

.box1{
    grid-area: 1 / 1 / 2 / 3;
}

假設我們要排版某個頁面,如下圖已經知道頁面上哪些區塊要放什麼樣的內容:

此時可以使用 grid-area 命名空間的方式預先命名某些空間,然後用 grid-template-areas 來排版,



Gutters / Alleys
另外如果希望Grid cells 之間有些分隔,可以用 column-gaprow-gap,或者直接使用 shorthand 寫法 gap。(寫的時候要注意有些瀏覽器只支援有前綴字的寫法:grid-column-gapgrid-row-gapgrid-gap

Overlapping
如果要重疊不同物件有兩種作法:

  1. overlapped using z-index
  2. overlapped by line numbers

在 Grid 給定 z-index 就是在物件上增加 z-index 屬性;而給予 line numbers 的作法則是先讓兩個物件佔同一行/列、並讓列或行有重疊到,如下改寫自MDN的範例item1 佔了 column lines 1-3 之間和 row lines 1-4的空間, 同時 item2 也佔了 column line 1 和 row lines 2-4 之間的空間。

.item1{
    grid-column: 1/3;
    grid-row: 1/4;
}

.item2{
    grid-column-start: 1;
    grid-row: 2/4;
}


Nesting grid and Subgrid

Nesting grid 就是把 容器內某個元素也當成容器 去排版這個元素內的子元素。

Working Draft Level 2 的 Grid 又出現另一種 Nesting grid 的排版概念 ─ Subgrid,但考量到目前這個屬性只支援 Firefox 71,所以暫不深入介紹了。


References


#frontend #css #note







Related Posts

NLP 簡介

NLP 簡介

發現fork後的專案少了分支

發現fork後的專案少了分支

一起來協作 MDN 翻譯吧!

一起來協作 MDN 翻譯吧!


Comments